// Login Page Component
import React, { useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { Link } from 'react-router-dom';
import { User, Key } from 'lucide-react';
import { API_ENDPOINTS } from '../config/api';

const LoginPage = () => {
  const [formData, setFormData] = useState({ loginName: '', password: '' });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const { login } = useAuth();

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const response = await fetch(API_ENDPOINTS.LOGIN, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          loginName: formData.loginName,
          password: formData.password,
          loginType: 'PASSWORD'
        }),
      });

      const data = await response.json();

      // --- 调试日志 ---
      console.log('--- 登录API响应详情 ---');
      console.log('Status Code:', response.status);
      console.log('Response OK:', response.ok);
      console.log('Response Body:', data);
      console.log('--------------------------');

      if (response.ok && data.code === 200) {
        // 只调用login更新状态，路由会自动处理跳转
        await login(data.data, data.data.token);
        // 此处不需要再做任何事，加载状态会持续直到页面跳转
      } else {
        setError(data.message || '用户名或密码错误');
        setLoading(false);
      }
    } catch (err) {
      setError('网络错误，登录失败');
      setLoading(false);
    }
  };

  return (
    <div className="auth-page">
      <div className="auth-container">
        <div className="auth-header">
          <h2>登录到 红小匠·AI</h2>
          <p>没有账号？ <Link to="/register">立即创建</Link></p>
        </div>
        <form onSubmit={handleSubmit} className="auth-form">
          {error && <p className="auth-error">{error}</p>}
          <div className="form-group">
            <User />
            <input type="text" name="loginName" placeholder="用户名或邮箱" required onChange={handleChange} disabled={loading} />
          </div>
          <div className="form-group">
            <Key />
            <input type="password" name="password" placeholder="密码" required onChange={handleChange} disabled={loading} />
          </div>
          <div className="form-options">
            <label>
              <input type="checkbox" name="rememberMe" disabled={loading} /> 记住我
            </label>
            <a href="#">忘记密码？</a>
          </div>
          <button type="submit" className="auth-button" disabled={loading}>
            {loading ? '登录中...' : '登录'}
          </button>
        </form>
      </div>
    </div>
  );
};

export default LoginPage; 